package Chapter06;

/**
 * 死锁的例子
 * 多个线程分别拥有不同的资源,而同时必须又需要对方释放资源才能继续运行下去,就会发生死锁.
 * Created by a on 2017/6/14.
 */
public class Test139 {
    public static void main(String[] args) {
        DeadLock deadLock1 = new DeadLock();
        DeadLock deadLock2 = new DeadLock();
        Thread t1 = new Thread(deadLock1);
        Thread t2 = new Thread(deadLock2);
        deadLock1.flag = true;
        deadLock2.flag = false;
        t1.start();
        t2.start();

    }
}

class DeadLock implements Runnable {

    public boolean flag;

    public static final Object o1 = new Object();

    public static final Object o2 = new Object();

    @Override
    public void run() {
        String threaddName = Thread.currentThread().getName();
        System.out.println(threaddName+":flag="+flag);

        if (flag == true){
            synchronized (o1){
                try {
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(threaddName+"进入同步块o1准备进入同步块o2");
                synchronized (o2){
                    System.out.println(threaddName+"已经进入同步块o2");
                }
            }
        }
        if (flag == false){
            synchronized (o2){
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                System.out.println(threaddName+"进入同步块o2，准备进入同步块o1");
                synchronized (o1){
                    System.out.println(threaddName+"已经进入同步块o1");
                }
            }
        }
    }
}
